<template>
  <div>
    <BasicTable @register="register" :dragable="true" @draggable-end="handleDragEnd">
      <template #headerCell="{ column }">
        <span v-if="column.dataIndex == '__ACTION__'">
          操作<Button type="link" @click="handleAdd">添加</Button>
        </span>
      </template>
      <template #bodyCell="{ column, index, record }">
        <FormItemRest v-if="['label', 'value'].includes(column.dataIndex as string)">
          <template v-if="view">
            {{ record[column.dataIndex as string] }}
          </template>
          <Input
            v-else
            v-model:value="mValue[index][column.dataIndex as string]"
            :placeholder="'请输入' + column.title"
          />
        </FormItemRest>
        <TableAction
          :actions="[
            {
              label: '删除',
              popConfirm: {
                title: '您确定删除该条记录吗？',
                confirm: handleDelete.bind(null, index),
              },
            },
          ]"
          v-else-if="column.dataIndex === '__ACTION__'"
        />
      </template>
    </BasicTable>
  </div>
</template>
<script setup lang="ts">
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { Button, Input, FormItemRest } from 'ant-design-vue';
  import { computed } from 'vue';

  defineOptions({
    inheritAttrs: false,
  });
  // 实现v-model:value
  const props = defineProps({
    value: {
      type: Array,
      default: () => [],
    },
    view: {
      type: Boolean,
      default: false,
    },
  });
  const emits = defineEmits(['update:value', 'change']);
  const mValue = computed<Array<any>>({
    get() {
      return props.value;
    },
    set(val) {
      emits('update:value', val);
      emits('change', val);
    },
  });
  const [register] = useTable({
    showIndexColumn: false,
    dataSource: mValue,
    pagination: false,
    scroll: {
      y: '100%',
    },
    columns: [
      {
        title: '-',
        dataIndex: '-',
        //edit: true,
        dragable: true,
        width: 30,
        ifShow: !props.view,
      },
      {
        title: '权限名',
        dataIndex: 'label',
        //edit: true,
      },
      {
        title: '权限码(sys:role:xx)',
        dataIndex: 'value',
        //edit: true,
      },
      {
        title: '操作',
        dataIndex: '__ACTION__',
        width: 120,
        align: 'center',
        ifShow: !props.view,
      },
    ],
  });
  const handleAdd = () => {
    mValue.value = [
      ...mValue.value,
      {
        label: '权限码' + mValue.value.length,
        value: '',
      },
    ];
  };
  const handleDelete = (index: number) => {
    mValue.value = mValue.value.filter((_, i) => i !== index);
  };
  const handleDragEnd = (e: any) => {
    // 删除旧的数据
    const [removed] = mValue.value.splice(e.oldIndex, 1);
    // 在newIndex后面插入删除的数据
    mValue.value.splice(e.newIndex, 0, removed);
    mValue.value = [...mValue.value];
  };
</script>
<style lang="less" scoped></style>
